package ioperations;

import book.Book;
import book.BookList;

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 姚东名
 * Date: 2024-06-01
 * Time: 23:58
 */
public class DelOperation implements Ioperation {
    @Override
    public void work(BookList bookList) {
        System.out.println("删除图书");

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入您要删除的书名：");
        String name = scanner.nextLine();
        //书架上有效的书本的个数：
        int currentSize = bookList.getUsedSize();

        int pos = -1;
        //找到这本书：遍历接口数组
        int i = 0;
        for (; i < currentSize; i++) {
            Book book = bookList.getBooks(i);
            if(book.getName().equals(name)) {
                pos = i;
                //找到就退出本循环
                break;
            }
        }
        if(i == currentSize) {
            System.out.println("没有您要删除的书本！");
            return;
        }
        //在这删除
        for (int j = pos; j < currentSize - 1; j++) {
            //把后一个数据往前移动，覆盖前一个数据
            //error：bookList[j] = bookList[j + 1];
            //这是面向对象程序设计：通过各个方法的协调完成需求

            //得到书架的下标：就可得到书本了 -> 拿到pos位置的下一本书
            Book book = bookList.getBooks(j + 1);
            //把后一个数据往前移动，覆盖前一个数据
            bookList.setBooks(j, book);
        }
        bookList.setBooks(currentSize - 1, null);
        //书架上的书本自减1
        bookList.setUsedSize(currentSize - 1);
        System.out.println("删除成功！");
    }
}
